package com.example.calculator_backend.controller;

import com.example.calculator_backend.pojo.LoanRequest;
import com.example.calculator_backend.pojo.LoanResult;
import com.example.calculator_backend.pojo.PaymentDetail;
import com.example.calculator_backend.service.LoanCalculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 贷款计算控制器
 * @author: hdr
 * @PACKAGE_NAME: com.example.calculator_backend.controller
 * @DATE: 2025/8/6
 */
@RestController
@RequestMapping("/api/loan")
@CrossOrigin(origins = "*", maxAge = 3600)
public class LoanController {

    private static final Logger logger = LoggerFactory.getLogger(LoanController.class);

    /**
     * 计算贷款
     * @param request 贷款请求参数
     * @return 贷款计算结果
     */
    @PostMapping("/calculate")
    public ResponseEntity<?> calculate(@RequestBody LoanRequest request) {
        try {
            logger.info("收到贷款计算请求: {}", request);
            
            // 参数验证
            if (request == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("请求参数不能为空"));
            }
            
            // 调用计算服务
            LoanResult result = LoanCalculator.calculate(request);
            
            logger.info("贷款计算完成，生成 {} 个月的还款计划", result.getSchedule().size());
            return ResponseEntity.ok(result);
            
        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            logger.error("贷款计算失败", e);
            return ResponseEntity.internalServerError().body(createErrorResponse("计算失败，请稍后重试"));
        }
    }

    /**
     * 获取贷款的每月还款详情（分页）
     * @param request 贷款请求参数
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @return 分页的每月还款详情
     */
    @PostMapping("/monthly-details")
    public ResponseEntity<?> getMonthlyDetails(
            @RequestBody LoanRequest request,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {
        try {
            logger.info("获取每月还款详情，页码: {}, 每页大小: {}", page, size);
            
            if (request == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("请求参数不能为空"));
            }
            
            if (page < 1 || size < 1 || size > 120) {
                return ResponseEntity.badRequest().body(createErrorResponse("页码必须大于0，每页大小必须在1-120之间"));
            }
            
            // 调用计算服务
            LoanResult result = LoanCalculator.calculate(request);
            List<PaymentDetail> allDetails = result.getSchedule();
            
            // 分页处理
            int totalMonths = allDetails.size();
            int totalPages = (int) Math.ceil((double) totalMonths / size);
            
            if (page > totalPages) {
                return ResponseEntity.badRequest().body(createErrorResponse("页码超出范围，总页数: " + totalPages));
            }
            
            int startIndex = (page - 1) * size;
            int endIndex = Math.min(startIndex + size, totalMonths);
            List<PaymentDetail> pageDetails = allDetails.subList(startIndex, endIndex);
            
            Map<String, Object> response = new HashMap<>();
            response.put("currentPage", page);
            response.put("pageSize", size);
            response.put("totalPages", totalPages);
            response.put("totalMonths", totalMonths);
            response.put("monthlyDetails", pageDetails);
            response.put("summary", Map.of(
                "monthlyPayment", result.getMonthlyPayment(),
                "totalInterest", result.getTotalInterest(),
                "totalRepayment", result.getTotalRepayment()
            ));
            
            logger.info("返回第 {} 页数据，共 {} 条记录", page, pageDetails.size());
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            logger.error("获取每月还款详情失败", e);
            return ResponseEntity.internalServerError().body(createErrorResponse("获取数据失败，请稍后重试"));
        }
    }

    /**
     * 获取指定月份的还款详情
     * @param request 贷款请求参数
     * @param month 月份（从1开始）
     * @return 指定月份的还款详情
     */
    @PostMapping("/month-detail/{month}")
    public ResponseEntity<?> getMonthDetail(
            @RequestBody LoanRequest request,
            @PathVariable int month) {
        try {
            logger.info("获取第 {} 个月的还款详情", month);
            
            if (request == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("请求参数不能为空"));
            }
            
            if (month < 1) {
                return ResponseEntity.badRequest().body(createErrorResponse("月份必须大于0"));
            }
            
            // 调用计算服务
            LoanResult result = LoanCalculator.calculate(request);
            List<PaymentDetail> allDetails = result.getSchedule();
            
            if (month > allDetails.size()) {
                return ResponseEntity.badRequest().body(createErrorResponse(
                    String.format("月份超出范围，贷款期限为 %d 个月", allDetails.size())));
            }
            
            PaymentDetail monthDetail = allDetails.get(month - 1);
            
            Map<String, Object> response = new HashMap<>();
            response.put("month", month);
            response.put("detail", monthDetail);
            response.put("summary", Map.of(
                "monthlyPayment", result.getMonthlyPayment(),
                "totalInterest", result.getTotalInterest(),
                "totalRepayment", result.getTotalRepayment()
            ));
            
            logger.info("返回第 {} 个月数据", month);
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            logger.error("获取月份还款详情失败", e);
            return ResponseEntity.internalServerError().body(createErrorResponse("获取数据失败，请稍后重试"));
        }
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> health() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "loan-calculator");
        response.put("timestamp", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok(response);
    }

    /**
     * 获取支持的贷款类型
     * @return 支持的贷款类型列表
     */
    @GetMapping("/loan-types")
    public ResponseEntity<Map<String, Object>> getLoanTypes() {
        Map<String, Object> response = new HashMap<>();
        response.put("loanTypes", new String[]{"商业贷款", "公积金贷款", "组合贷款"});
        response.put("repaymentTypes", new String[]{"等额本息", "等额本金", "先息后本"});
        return ResponseEntity.ok(response);
    }

    /**
     * 创建错误响应
     * @param message 错误消息
     * @return 错误响应对象
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", true);
        error.put("message", message);
        error.put("timestamp", System.currentTimeMillis());
        return error;
    }
}
